package com.app.application;

import java.io.File;

import android.app.AlarmManager;
import android.app.Application;
import android.content.Context;
import android.support.multidex.MultiDexApplication;

import com.app.config.UserConfig;
import com.app.utils.Const;
import com.app.utils.DBHelper;
import com.app.utils.LocationUtil;
import com.app.utils.SdLocal;
import com.app.utils.Setting;
import com.app.utils.Utils;
import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.baidu.mapapi.SDKInitializer;
import com.bugtags.library.Bugtags;
import com.bugtags.library.BugtagsOptions;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UmengHelper;
import com.core.lib.utils.main.UtilityBase;
import com.iflytek.cloud.SpeechUtility;
import com.lepu.app.fun.chat.core.ChatDAO;
import com.lepu.app.fun.chat.core.ChatManager;
import com.lepu.app.fun.index.remind.Alarm;
import com.lepu.app.main.push.PushUtils;
import com.lepu.app.main.service.AppService;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lepu.app.usercenter.util.UserCenterUtil;
import com.lepu.pasm.R;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.decode.BaseImageDecoder;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;

import org.jivesoftware.smack.SmackAndroid;

public class MyApplication extends MultiDexApplication {

	private static MyApplication mInstance = null;
	public String mBaiduUserId = "";
	public String mBaiduChannelId = "";
	public String mGeTuiChannelId = "";
	public boolean mPushGetSuccessBaidu = false;
	public boolean mPushGetSuccessGeTui = false;
	public boolean mGetSuccessLocation = false;

	private LoginInfo mLoginInfo = null;// 登录info
	public LoginInfo mTempLoginInfo = new LoginInfo();// 注册成功，完善资料前的info
	
	public static AlarmManager alarmManager;

	@Override
	public void onCreate() {
		// 讯飞语音
		SpeechUtility.createUtility(MyApplication.this, "appid=570472ce");
		super.onCreate();
		mInstance = this;

		init();
	}

	private void init() {
		initImageLoader(this);

		// update login info
		String value = UserConfig.getConfigString(getApplicationContext(),
				Const.CONFIG_APP_LOGIN_INFO, "");

		LogUtilBase.LogD(null, "user_info==" + value);
		LoginInfo loginInfo = LoginInfo.parseLoginInfo(value);
		setLoginInfo(loginInfo);

		// 添加新包 需要先进行初始化
		SmackAndroid.init(this);

		//UtilityBase.STATUS_BAR_CHANGE = false;//同心不要顶部bar改变颜色

		UmengHelper.openActivityDurationTrack();
		UmengHelper.updateOnlineConfig(this);
		UmengHelper.EnableEncrypt(true);
		UmengHelper.setDebug(Setting.UmengDebug);// umengFlag

		UtilityBase.DEBUG = Setting.NeedCustomLog;// Setting.DEBUG

		//初始化Bugtags
		try {
			BugtagsOptions options = new BugtagsOptions.Builder().
					trackingLocation(true).//是否获取位置，默认 true
					trackingCrashLog(true).//是否收集crash，默认 true
					trackingConsoleLog(true).//是否收集console log，默认 true
					trackingUserSteps(true).//是否收集用户操作步骤，默认 true
					build();
			int btgValue = Bugtags.BTGInvocationEventBubble;
			if(!Setting.DEBUG){
				btgValue = Bugtags.BTGInvocationEventNone;
			}
			Bugtags.start("57f1fa174e0bd9dd180e17e849d80cee", this,
					btgValue, options);
		}catch (Exception e){

		}

		// 初始化，检查数据库
		DBHelper.checkDatabase(this);

		// 启动AppService  检查医患关系service   当收到医生端发来的消息，在service请求医患关系接口
		AppService.startAppService(this);

		checkIfDb();
		clearOldDb();
		
		alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);

	    //设置最近的闹钟
	    Alarm.setRemindNextAlarm(this);

		//定时清理缓存
		Utils.cleanByTime(this);
		
		//初始化百度map
	    SDKInitializer.initialize(this);

		//download so testbugtags-lib-1.2.7.jar
		//Utils.downloadSo(mInstance);

		UserCenterUtil.getTellPhone();
	}

	public static MyApplication getInstance() {
		return mInstance;
	}

	public LoginInfo getLoginInfo() {
		return mLoginInfo;
	}

	public void setLoginInfo(LoginInfo loginInfo) {
		if (loginInfo == null) {
			this.mLoginInfo = new LoginInfo();
		} else {
			this.mLoginInfo = loginInfo;
		}
	}

	@SuppressWarnings("deprecation")
	public static void initImageLoader(Context context) {
		// This configuration tuning is custom. You can tune every option, you
		// may tune some of them,
		// or you can create default configuration by
		// ImageLoaderConfiguration.createDefault(this);
		// method.

		String path = SdLocal.getTempFolder(context);
		File cacheDir = new File(path);

		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				context)
				.memoryCacheExtraOptions(480, 800)
				// default = device screen dimensions
				.discCacheExtraOptions(480, 800, null)
				.threadPoolSize(3)
				// default
				.threadPriority(Thread.NORM_PRIORITY - 1)
				// default
				.tasksProcessingOrder(QueueProcessingType.FIFO)
				// default
				.denyCacheImageMultipleSizesInMemory()
				.memoryCache(new LruMemoryCache(100 * 1024 * 1024))
				.memoryCacheSize(100 * 1024 * 1024).memoryCacheSizePercentage(13) // default
				.discCache(new UnlimitedDiskCache(cacheDir))// default
				.discCacheSize(1000 * 10 * 1024 * 1024) // 缓冲大小
				// .discCacheFileCount(100) // 缓冲文件数目
				.discCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
				.imageDecoder(new BaseImageDecoder(false)) // default
				.imageDownloader(
						new BaseImageDownloader(context, 10 * 1000, 30 * 1000)) // connectTimeout
																				// (5
																				// s),
																				// readTimeout
																				// (20
																				// s)
				.defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
				.writeDebugLogs().build();

		// Initialize ImageLoader with configuration.
		ImageLoader.getInstance().init(config);
	}

	private void clearOldDb()
	{
		File fileCity = getDatabasePath(DBHelper.DATABASE_NAME_CITY_OLD);
		File fileCity2 = getDatabasePath(DBHelper.DATABASE_NAME_CITY_OLD+"-journal");
		if(fileCity.exists())
		{
			fileCity.delete();
		}

		if(fileCity2.exists())
		{
			fileCity2.delete();
		}
	}

	/**
	 *
	 */
	private void checkIfDb() {
		DBHelper dbHelper = DBHelper.getInstance(DBHelper.DATABASE_NAME_MAIN);
		if (dbHelper != null) {

			// 是否有alarm表
			boolean flagAlarm = dbHelper.isTableExists("alarm");
			LogUtilBase.LogD(null, "alarm ===========>" + flagAlarm);
			if (!flagAlarm) {
				String sql = getString(R.string.create_table_alarm);
				dbHelper.executeNonQuery(sql, new Object[] {});
			}

			// 是否有MsgBbs表
			boolean flagBbs = dbHelper.isTableExists("MsgBbs");
			LogUtilBase.LogD(null, "MsgBbs ===========>" + flagBbs);
			if (!flagBbs) {
				String sql = getString(R.string.create_table_my_message_bbs);
				dbHelper.executeNonQuery(sql, new Object[] {});
			}

			// 是否有MsgSystem表
			boolean flagSystem = dbHelper.isTableExists("MsgSystem");
			LogUtilBase.LogD(null, "MsgSystem ===========>" + flagSystem);
			if (!flagBbs) {
				String sql = getString(R.string.create_table_my_message_system);
				dbHelper.executeNonQuery(sql, new Object[] {});
			}

			// 是否有newRead表
			boolean flagRead = dbHelper.isTableExists("NewRead");
			LogUtilBase.LogD(null, "NewRead ===========>" + flagSystem);
			if (!flagRead) {
				String sql = getString(R.string.create_table_newRead);
				dbHelper.executeNonQuery(sql, new Object[] {});
			}
			//======================================
			// 是否有讲座message表
			boolean flagChatRoomMessage = dbHelper.isTableExists("chatRoom_Message");
			LogUtilBase.LogD(null, "chatRoom_Message ===========>" + flagChatRoomMessage);
			if (!flagChatRoomMessage) {
				String sql = getString(R.string.create_table_chatRoom_Message);
				dbHelper.executeNonQuery(sql, new Object[] {});
			}

			// 是否有讲座session表
			boolean flagChatRoomSession = dbHelper.isTableExists("chatRoom_Session");
			LogUtilBase.LogD(null, "chatRoom_Session ===========>" + flagChatRoomSession);
			if (!flagChatRoomSession) {
				String sql = getString(R.string.create_table_chatRoom_Message);
				dbHelper.executeNonQuery(sql, new Object[] {});
			}

			//系统消息表 加targetUrl字段
			boolean flagMsgSystem = dbHelper.isColumeExists("MsgSystem",
					"targetUrl");
			LogUtilBase.LogD(null, "MsgSystem add targetUrl===========>" + flagMsgSystem);
			if (!flagMsgSystem) {
				String sql1 = "alter table MsgSystem add column targetUrl TEXT";
				dbHelper.executeNonQuery(sql1, new Object[] {});
			}

			//是否有TimeStamp字段
			boolean flagChatMessage = dbHelper.isColumeExists("chat_Message",
					"TimeStamp");
			LogUtilBase.LogD(null, "chat_Message ===========>" + flagChatMessage);
			if (!flagChatMessage) {
				String sql1 = "alter table chat_Message add column TimeStamp BIGINT default 0";

				dbHelper.executeNonQuery(sql1, new Object[]{});

				//删除老的私聊数据
				ChatManager.getInstance().resetChatMessages();
			}
		}
	}

}
